package action

import (
	"fmt"
	"gitee.com/dromara/carbon/v2"
	"github.com/spf13/cast"
	"server/component"
	"server/im/entity"
	"server/im/online"
	"server/im/protocol"
	//"github.com/spf13/cast"
	//"github.com/uniplaces/carbon"
	//"server/component"
	//"server/dao"
	//"server/im/model"
	//"server/im/protocol"
)

// 聊天室在线
func ActionChatroomMember(ctx entity.ServiceContext) {

	online := online.OnlineMap.GetOnline()
	var onlineList []map[string]string
	for _, onlineItem := range online {
		onlineList = append(onlineList, map[string]string{
			"uuid": onlineItem.User.Uuid,
			"name": onlineItem.User.Name,
		})
	}

	msgBytes, _ := component.JsonEncode(onlineList)

	ctx.RespChan <- entity.CoreResultModel{
		CoreOutModel: entity.CoreOutModel{
			GatewayOutModel: entity.GatewayOutModel{
				Data: msgBytes,
				Cmd:  protocol.RespChatroomMember,
			},
			GatewayId:    ctx.GatewayId,
			MsgType:      entity.MsgTypeNormal,
			ReceiverType: entity.ReceiverTypeSingle,
			Clients:      []string{ctx.UserUni},
		},
		ResultType: entity.CoreResultTypeOne,
	}
}

// 聊天室消息
func ActionChatroomMsg(ctx entity.ServiceContext) {
	var reqData map[string]string
	component.JsonDecode(ctx.Data, &reqData)
	fmt.Println(reqData)

	msg, ok := reqData["msg"]
	if ok {
		msgStr := cast.ToString(msg)

		sendInfo := map[string]string{
			"msg":  msgStr,
			"name": ctx.User.Name,
			"uuid": ctx.User.Uuid,
			"time": carbon.Now().ToDateTimeString(),
		}
		msgBytes, err := component.JsonEncode(sendInfo)
		if err != nil {
			component.Log.Error(err)
			return
		}

		ctx.RespChan <- entity.CoreResultModel{
			CoreOutModel: entity.CoreOutModel{
				GatewayOutModel: entity.GatewayOutModel{
					Data: msgBytes,
					Cmd:  protocol.RespChatroomMsg,
				},
				GatewayId:    ctx.GatewayId,
				MsgType:      entity.MsgTypeNormal,
				ReceiverType: entity.ReceiverTypeBroadcast,
				Clients:      []string{},
			},
			ResultType: entity.CoreResultTypeAll,
		}
	}
}
